﻿//
// Lightbox Gallery Module for DotNetNuke
// Project Contributors - Will Strohl (http://www.WillStrohl.com), Armand Datema (http://www.schwingsoft.com)
//
//Copyright (c) 2009-2013, Will Strohl
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are 
//permitted provided that the following conditions are met:
//
//Redistributions of source code must retain the above copyright notice, this list of 
//conditions and the following disclaimer.
//
//Redistributions in binary form must reproduce the above copyright notice, this list 
//of conditions and the following disclaimer in the documentation and/or other 
//materials provided with the distribution.
//
//Neither the name of Will Strohl, Armand Datema, Lightbox Gallery, nor the names of its contributors may be 
//used to endorse or promote products derived from this software without specific prior 
//written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
//EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
//OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
//SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
//TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
//BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
//CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
//DAMAGE.
//

//INSTANT C# NOTE: Formerly VB project-level imports:

using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using System;
using System.Collections;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.FileSystem;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using DotNetNuke.UI.Skins;
using DotNetNuke.UI.Skins.Controls;

namespace WillStrohl.Modules.Lightbox
{

    public partial class EditLightbox : WnsPortalModuleBase
    {

        #region  Private Members

        private int p_AlbumId = Null.NullInteger;
        private string p_FolderHandler = string.Empty;

        private string c_AutoCompleteKey = "jquery.autocomplete";
        
        #endregion

        #region  Public Properties

        protected int AlbumId
        {
            get
            {
                if (!(p_AlbumId > Null.NullInteger))
                {
                    object objGallery = Request.Params["AlbumId"];
                    if (objGallery != null)
                    {
                        p_AlbumId = int.Parse(objGallery.ToString(), System.Globalization.NumberStyles.Integer);
                    }
                    else
                    {
                        p_AlbumId = Null.NullInteger;
                    }
                }

                return p_AlbumId;
            }
        }

        protected string FolderHandler
        {
            get
            {
                if (!(string.IsNullOrEmpty(p_FolderHandler)))
                {
                    return p_FolderHandler;
                }

                p_FolderHandler = string.Concat(ControlPath, "folders.ashx");

                return p_FolderHandler;
            }
        }

        #endregion

        #region  Event Handlers

        /// <summary>
        /// OnInit - initialization of the module
        /// </summary>
        /// <param name="e"></param>
        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            Load += new EventHandler(Page_Load);
            cmdUpdate.Click += new EventHandler(cmdUpdate_Click);
            cmdDelete.Click += new EventHandler(cmdDelete_Click);
            cmdCancel.Click += new EventHandler(cmdCancel_Click);
            cmdDeleteThumbnails.Click += new EventHandler(cmdDeleteThumbnails_Click);
        }

        private void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (AllowedToEditModule() == false)
                {
                    Response.Redirect(GetDefaultViewUrl());
                }

                if (!Page.IsPostBack)
                {
                    BindData();
                }
            }
            catch (Exception exc) // Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc, IsEditable);
            }
        }

        private void cmdUpdate_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                SaveGallery();
            }
        }

        private void cmdDelete_Click(object sender, EventArgs e)
        {
            var ctlGallery = new LightboxController();
            ctlGallery.DeleteLightbox(AlbumId);

            SendToDefaultView();
        }

        private void cmdCancel_Click(object sender, EventArgs e)
        {
            SendToDefaultView();
        }

        private void cmdDeleteThumbnails_Click(object sender, EventArgs e)
        {
            DeleteThumbnails();
            SendToDefaultView();
        }

        #endregion

        #region  Private Helper Functions

        private void BindData()
		{

			LocalizeModule();

			// hide the delete button when adding a new album to the module
			cmdDelete.Visible = (AlbumId > Null.NullInteger);

			cmdDeleteThumbnails.Visible = (AlbumId > Null.NullInteger);

			if (! Page.IsPostBack)
			{

				if (lstTitlePosition.Items.Count == 0)
				{
					lstTitlePosition.Items.Add(new ListItem(GetLocalizedString("lstTitlePosition.Item.Outside"), "outside"));
					lstTitlePosition.Items.Add(new ListItem(GetLocalizedString("lstTitlePosition.Item.Inside"), "inside"));
					lstTitlePosition.Items.Add(new ListItem(GetLocalizedString("lstTitlePosition.Item.Over"), "over"));
					lstTitlePosition.Items.Insert(0, new ListItem("---"));
				}

				if (lstTransition.Items.Count == 0)
				{
					lstTransition.Items.Add(new ListItem(GetLocalizedString("lstTransition.Item.Elastic"), "elastic"));
					lstTransition.Items.Add(new ListItem(GetLocalizedString("lstTransition.Item.Fade"), "fade"));
					lstTransition.Items.Add(new ListItem(GetLocalizedString("lstTransition.Item.None"), "none"));
					lstTransition.Items.Insert(0, new ListItem("---"));
				}

				if (AlbumId > Null.NullInteger)
				{

					// Load the lightbox album information into the form
					var ctlLightbox = new LightboxController();
					var objAlbum = new LightboxInfo();
					objAlbum = ctlLightbox.GetLightbox(AlbumId);

					txtGalleryName.Text = Server.HtmlDecode(objAlbum.GalleryName);
					txtGalleryDescription.Text = Server.HtmlDecode(objAlbum.GalleryDescription);
					cboGalleryFolder.Text = Server.HtmlDecode(objAlbum.GalleryFolder);
					chkHideTitleDescription.Checked = objAlbum.HideTitleDescription;

					var objSetting = new SettingInfo();
					objSetting = ctlLightbox.GetSettings(objAlbum.LightboxId);

					txtPadding.Text = objSetting.Padding.ToString();
					txtMargin.Text = objSetting.Margin.ToString();
					chkOpacity.Checked = objSetting.Opacity;
					chkModal.Checked = objSetting.Modal;
					chkCyclic.Checked = objSetting.Cyclic;
					chkOverlayShow.Checked = objSetting.OverlayShow;
					txtOverlayOpacity.Text = objSetting.OverlayOpacity.ToString();
					txtOverlayColor.Text = objSetting.OverlayColor;
					chkTitleShow.Checked = objSetting.TitleShow;
					lstTitlePosition.Items.FindByValue(objSetting.TitlePosition).Selected = true;
					lstTransition.Items.FindByValue(objSetting.Transition).Selected = true;
					txtSpeed.Text = objSetting.Speed.ToString();
					txtChangeSpeed.Text = objSetting.ChangeSpeed.ToString();
					chkShowCloseButton.Checked = objSetting.ShowCloseButton;
					chkShowNavArrows.Checked = objSetting.ShowNavArrows;
					chkEnableEscapeButton.Checked = objSetting.EnableEscapeButton;
					txtOnStart.Text = objSetting.OnStart;
					txtOnCancel.Text = objSetting.OnCancel;
					txtOnComplete.Text = objSetting.OnComplete;
					txtOnCleanup.Text = objSetting.OnCleanup;
					txtOnClosed.Text = objSetting.OnClosed;

				}
				else
				{

					// Set Default Values:
					// The empty settings object will have the default values already assigned
					var objSetting = new SettingInfo();

					txtPadding.Text = objSetting.Padding.ToString();
					txtMargin.Text = objSetting.Margin.ToString();
					chkOpacity.Checked = objSetting.Opacity;
					chkModal.Checked = objSetting.Modal;
					chkCyclic.Checked = objSetting.Cyclic;
					chkOverlayShow.Checked = objSetting.OverlayShow;
					txtOverlayOpacity.Text = objSetting.OverlayOpacity.ToString();
					txtOverlayColor.Text = objSetting.OverlayColor;
					chkTitleShow.Checked = objSetting.TitleShow;
					lstTitlePosition.Items.FindByValue(objSetting.TitlePosition).Selected = true;
					lstTransition.Items.FindByValue(objSetting.Transition).Selected = true;
					txtSpeed.Text = objSetting.Speed.ToString();
					txtChangeSpeed.Text = objSetting.ChangeSpeed.ToString();
					chkShowCloseButton.Checked = objSetting.ShowCloseButton;
					chkShowNavArrows.Checked = objSetting.ShowNavArrows;
					chkEnableEscapeButton.Checked = objSetting.EnableEscapeButton;
					txtOnStart.Text = objSetting.OnStart;
					txtOnCancel.Text = objSetting.OnCancel;
					txtOnComplete.Text = objSetting.OnComplete;
					txtOnCleanup.Text = objSetting.OnCleanup;
					txtOnClosed.Text = objSetting.OnClosed;

				}

				var ctlFolder = new FolderController();
				IEnumerable<IFolderInfo> collFolder = FolderManager.Instance.GetFolders(PortalId);

				var lstFolder = new List<IFolderInfo>();

				foreach(IFolderInfo oFolder in collFolder)
				{
					if (! (string.IsNullOrEmpty(oFolder.FolderPath)))
					{
						lstFolder.Add(oFolder);
					}
				}

				cboGalleryFolder.AllowCustomText = true;
				cboGalleryFolder.MarkFirstMatch = true;
				cboGalleryFolder.ClearSelection();
				cboGalleryFolder.Items.Clear();
				cboGalleryFolder.DataTextField = "FolderPath";
				cboGalleryFolder.DataValueField = "FolderPath";
				cboGalleryFolder.DataSource = lstFolder;
				cboGalleryFolder.DataBind();

			}

		}

        private void LocalizeModule()
        {

            // localize the text
            cmdCancel.Text = GetLocalizedString("cmdCancel.Text");
            cmdDelete.Text = GetLocalizedString("cmdDelete.Text");
            cmdDeleteThumbnails.Text = GetLocalizedString("cmdDeleteThumbnails.Text");
            cmdUpdate.Text = GetLocalizedString("cmdUpdate.Text");
            vsError.HeaderText = string.Format("<span class=\"NormalBold\">{0}</span>", GetLocalizedString("vsError.HeaderText"));
            rfvGalleryName.ErrorMessage = GetLocalizedString("rfvGalleryName.ErrorMessage");
            rfvGalleryFolder.ErrorMessage = GetLocalizedString("rfvGalleryFolder.ErrorMessage");
            rfvGalleryDescription.ErrorMessage = GetLocalizedString("rfvGalleryDescription.ErrorMessage");

            Skin.AddModuleMessage(this, GetLocalizedString("lblFormMessage.Text"), ModuleMessage.ModuleMessageType.BlueInfo);

            rfvPadding.ErrorMessage = GetLocalizedString("rfvPadding.ErrorMessage");
            revPadding.ErrorMessage = GetLocalizedString("revPadding.ErrorMessage");
            rfvMargin.ErrorMessage = GetLocalizedString("rfvMargin.ErrorMessage");
            revMargin.ErrorMessage = GetLocalizedString("revMargin.ErrorMessage");
            rfvOverlayOpacity.ErrorMessage = GetLocalizedString("rfvOverlayOpacity.ErrorMessage");
            revOverlayOpacity.ErrorMessage = GetLocalizedString("revOverlayOpacity.ErrorMessage");
            rfvOverlayColor.ErrorMessage = GetLocalizedString("rfvOverlayColor.ErrorMessage");
            rfvTitlePosition.ErrorMessage = GetLocalizedString("rfvTitlePosition.ErrorMessage");
            rfvTransition.ErrorMessage = GetLocalizedString("rfvTransition.ErrorMessage");
            rfvSpeed.ErrorMessage = GetLocalizedString("rfvSpeed.ErrorMessage");
            revSpeed.ErrorMessage = GetLocalizedString("revSpeed.ErrorMessage");
            rfvChangeSpeed.ErrorMessage = GetLocalizedString("rfvChangeSpeed.ErrorMessage");
            revChangeSpeed.ErrorMessage = GetLocalizedString("revChangeSpeed.ErrorMessage");

        }

        private void SaveGallery()
        {

            var ctlGallery = new LightboxController();
            var ctlSecurity = new PortalSecurity();
            var oGallery = new LightboxInfo();

            if (AlbumId > Null.NullInteger)
            {
                oGallery = ctlGallery.GetLightbox(AlbumId);
            }

            oGallery.GalleryDescription = ctlSecurity.InputFilter(txtGalleryDescription.Text, PortalSecurity.FilterFlag.NoScripting);
            oGallery.GalleryFolder = ctlSecurity.InputFilter(cboGalleryFolder.Text, PortalSecurity.FilterFlag.NoScripting);
            oGallery.GalleryName = ctlSecurity.InputFilter(txtGalleryName.Text, PortalSecurity.FilterFlag.NoScripting);
            oGallery.HideTitleDescription = chkHideTitleDescription.Checked;
            oGallery.ModuleId = ModuleId;
            oGallery.LastUpdatedBy = UserId;

            var oSettings = ctlGallery.GetSettings(AlbumId);

            if (oSettings == null)
            {
                oSettings = new SettingInfo();
            }

            oSettings.ChangeSpeed = int.Parse(txtChangeSpeed.Text, System.Globalization.NumberStyles.Integer);
            oSettings.Cyclic = chkCyclic.Checked;
            oSettings.EnableEscapeButton = chkEnableEscapeButton.Checked;
            oSettings.Margin = int.Parse(txtMargin.Text, System.Globalization.NumberStyles.Integer);
            oSettings.Modal = chkModal.Checked;
            oSettings.OnCancel = txtOnCancel.Text;
            oSettings.OnCleanup = txtOnCleanup.Text;
            oSettings.OnClosed = txtOnClosed.Text;
            oSettings.OnComplete = txtOnComplete.Text;
            oSettings.OnStart = txtOnStart.Text;
            oSettings.Opacity = chkOpacity.Checked;
            oSettings.OverlayColor = txtOverlayColor.Text;
            oSettings.OverlayOpacity = decimal.Parse(txtOverlayOpacity.Text, System.Globalization.NumberStyles.Float);
            oSettings.OverlayShow = chkOverlayShow.Checked;
            oSettings.Padding = int.Parse(txtPadding.Text, System.Globalization.NumberStyles.Integer);
            oSettings.ShowCloseButton = chkShowCloseButton.Checked;
            oSettings.ShowNavArrows = chkShowNavArrows.Checked;
            oSettings.Speed = int.Parse(txtSpeed.Text, System.Globalization.NumberStyles.Integer);
            oSettings.TitlePosition = lstTitlePosition.SelectedValue;
            oSettings.TitleShow = chkTitleShow.Checked;
            oSettings.Transition = lstTransition.SelectedValue;

            if (AlbumId > Null.NullInteger)
            {
                oGallery.LightboxId = AlbumId;
                ctlGallery.UpdateLightbox(oGallery);
                ctlGallery.UpdateSetting(oSettings);
            }
            else
            {
                oSettings.LightboxId = ctlGallery.AddLightbox(oGallery);
                ctlGallery.AddSetting(oSettings);
            }

            SendToDefaultView();

        }

        private void DeleteThumbnails()
		{

			var ctlLightbox = new LightboxController();
			var oLightbox = ctlLightbox.GetLightbox(AlbumId);
			var strFolderName = oLightbox.GalleryFolder;

			// get a list of the files in the lightbox directory
			if (Regex.IsMatch(strFolderName, LightboxController.FOLDER_NAME_MATCH_PATTERN))
			{
				strFolderName = Regex.Replace(strFolderName, LightboxController.FOLDER_NAME_REPLACE_PATTERN, LightboxController.FOLDER_NAME_REPLACEMENT_PATTERN);
			}

			if (FolderManager.Instance.FolderExists(PortalId, strFolderName))
			{

				IFolderInfo oFolder = FolderManager.Instance.GetFolder(PortalId, strFolderName);
				ArrayList arrImages = null;

				// parse for each thumbnail
				arrImages = LightboxController.VerifiedFileList(FolderManager.Instance.GetFiles(oFolder));

				// delete the thumbnail
				foreach(IFileInfo oImage in arrImages)
				{
					string strThumbnail = LightboxController.GetThumbnailImageName(oImage.FileName, PortalSettings, false);
					if (FileManager.Instance.FileExists(oFolder, strThumbnail))
					{
						try
						{
							IFileInfo oThumbnail = FileManager.Instance.GetFile(oFolder, strThumbnail);
							FileManager.Instance.DeleteFile(oThumbnail);
						}
						catch (Exception ex)
						{
							Exceptions.LogException(ex);
						}
					}
				}

			}

		}

        private void SendToDefaultView()
        {
            Response.Redirect(GetDefaultViewUrl());
        }

        private void HandleException(Exception exc)
        {
            Exceptions.LogException(exc);
            if (UserInfo.IsSuperUser || UserInfo.UserID == PortalSettings.AdministratorId)
            {
                Skin.AddModuleMessage(this, string.Concat(exc.Message, "<br />", exc.StackTrace), ModuleMessage.ModuleMessageType.RedError);
            }
            else
            {
                Skin.AddModuleMessage(this, exc.Message, ModuleMessage.ModuleMessageType.RedError);
            }
        }

        #endregion
        
    }

}